package com.yc.edu.service.impl;

import cn.hutool.core.lang.hash.Hash;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yc.edu.dao.CourseDAO;
import com.yc.edu.pojo.*;
import com.yc.edu.service.CourseService;
import com.yc.edu.service.PostCommentsService;
import com.yc.edu.service.ReCourseService;
import com.yc.edu.service.UserService;
import com.yc.edu.utils.PageUtils;
import com.yc.edu.vo.dto.CourseWithCommentsDTO;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author YC
 * @version 1.0
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseDAO, Course> implements CourseService {
    @Resource
    PostCommentsService postCommentsService;

    @Resource
    ReCourseService reCourseService;

    @Resource
    UserService userService;

    public HashMap<String,List<Course>> getCoursesByUserId(String userId) {

//        if(userService.getById(userId) == null)
//            return null;

        HashMap<String,List<Course>> map = new HashMap<>();

        ReCourse reCourse = reCourseService.getById(userId);

        System.out.println(reCourse);

        String[] coursesId = reCourse.getCourses().split(",");
        String[] recommendsId = reCourse.getRecommend().split(",");

        List<Course> selectedCourses = listByIds(Arrays.asList(coursesId));
        List<Course> recommendedCourses = listByIds(Arrays.asList(recommendsId));

        map.put("selectedCourses", selectedCourses);
        map.put("recommendedCourses", recommendedCourses);

        return map;
    }

    @Override
    public PageUtils queryInfo(Map<String, Object> params) {
        QueryWrapper<Course> wrapper = new QueryWrapper<>();
        String keyword = (String) params.get("keyword");
        String sortBy = (String) params.get("sortBy"); // 获取排序方式

        if (StringUtils.hasText(keyword)) {
            wrapper.like("name", keyword).or()
                    .eq("teacherName", keyword).or()
                    .eq("schoolName", keyword);
        }

        // 1.价格排序
        if ("price".equals(sortBy)) {
            wrapper.orderByAsc("price");
        } else if ("pop".equals(sortBy)) {
            // 2.热度排序（订阅人数）
            wrapper.orderByDesc("enrollCount");
        } else {
            // 3.默认排序(综合)
            // 综合排序：订阅人数、时间、价格随机组合排序
            wrapper.orderByDesc("enrollCount")
                    .orderByDesc("startTime")
                    .orderByAsc("price")
                    .orderByAsc("id");
        }

        // 获取课程分页数据
        IPage<Course> coursePage = page(
                new Query<Course>().getPage(params),
                wrapper
        );

        // 映射每门课程的详细信息
        List<CourseWithCommentsDTO> courseWithCommentsList = coursePage.getRecords().stream().map(course -> {
            int courseId = course.getId();

            // 查询课程的评论，按内容长度排序，仅保留前 5 条
            List<PostComments> topComments = postCommentsService.list(
                    new QueryWrapper<PostComments>()
                            .eq("course_id", courseId)
                            .orderByDesc("LENGTH(content)")
                            .last("LIMIT 5")
            );

            // 封装课程和评论信息
            CourseWithCommentsDTO courseWithComments = new CourseWithCommentsDTO();
            courseWithComments.setCourse(course);
            courseWithComments.setTopComments(topComments);

            return courseWithComments;
        }).collect(Collectors.toList());

        // 如果是综合排序，随机打乱最终列表
        if (!StringUtils.hasText(sortBy)) {
            Collections.shuffle(courseWithCommentsList);
        }

        Set<String> names = new HashSet<>();
        courseWithCommentsList = courseWithCommentsList.stream()
                .filter(course -> names.add(course.getCourse().getName()))
                .collect(Collectors.toList());

        // 返回分页结果
        return new PageUtils(courseWithCommentsList, (int) coursePage.getTotal(),
                (int) coursePage.getSize(), (int) coursePage.getCurrent());
    }


//    @Override
//    public PageUtils queryInfo(Map<String, Object> params) {
//        QueryWrapper<Course> wrapper = new QueryWrapper<>();
//        String keyword = (String) params.get("keyword");
//
//        if (StringUtils.hasText(keyword)) {
//            wrapper.like("name", keyword).or()
//                    .eq("teacherName", keyword).or()
//                    .eq("schoolName", keyword).or()
//                    .orderByDesc("enrollCount");
//        }
//
//        // 获取课程分页数据
//        IPage<Course> coursePage = page(
//                new Query<Course>().getPage(params),
//                wrapper
//        );
//
//        // 映射每门课程的详细信息
//        List<CourseWithCommentsDTO> courseWithCommentsList = coursePage.getRecords().stream().map(course -> {
//            int courseId = course.getId();
//
//            // 查询课程的评论，按内容长度排序，仅保留前 5 条
//            List<PostComments> topComments = postCommentsService.list(
//                    new QueryWrapper<PostComments>()
//                            .eq("course_id", courseId)
//                            .orderByDesc("LENGTH(content)")
//                            .last("LIMIT 5")
//            );
//
//            // 封装课程和评论信息
//            CourseWithCommentsDTO courseWithComments = new CourseWithCommentsDTO();
//            courseWithComments.setCourse(course);
//            courseWithComments.setTopComments(topComments);
//
//            return courseWithComments;
//        }).collect(Collectors.toList());
//
//        // 返回分页结果
//        return new PageUtils(courseWithCommentsList, (int) coursePage.getTotal(),
//                (int) coursePage.getSize(), (int) coursePage.getCurrent());
//    }
}
